/**
 * @file snake.cpp
 * @author Henrik Ojanen
 * @version 1.0
 * @date 6.4.2011
 */

#include "snake.h"

Snake::Snake(int x, int y)
{
	blocks[0] = new Block(x, y);
	blocks[1] = new Block(x-1, y);
	blocks[2] = new Block(x-2, y);

	length = 3;
}

Snake::~Snake()
{
	for(int i=0; i<length; i++)
	{
		delete blocks[i];
	}
}

void Snake::move(int x, int y)
{
	for(int i=length-1; i>0; i--)
    {
        if(!(blocks[i]->getX() == blocks[i-1]->getX() && blocks[i]->getY() == blocks[i-1]->getY()))
			blocks[i]->jumpTo(blocks[i-1]->getX(), blocks[i-1]->getY());
    }

	blocks[0]->jumpTo(blocks[0]->getX()+x, blocks[0]->getY()+y);
}

bool Snake::collision(Block* block)
{
	if(blocks[0]->getX() == block->getX() && blocks[0]->getY() == block->getY())
		return true;
	return false;
}

void Snake::addLength()
{
	blocks[length++] = new Block(blocks[length-2]->getX(), blocks[length-2]->getY());
}

bool Snake::outsideRectangle(int x1, int y1, int x2, int y2)
{
	if(blocks[0]->getX() < x1 || blocks[0]->getY() < y1 ||
        blocks[0]->getX() > x2 || blocks[0]->getY() > y2)
        return true;

	return false;
}

bool Snake::collisionWithItself()
{
	for(int i=1; i<length; i++)
    {
		if(blocks[0]->getX() == blocks[i]->getX() && blocks[0]->getY() == blocks[i]->getY())
            return true;
    }

	return false;
}

int Snake::getX()
{
	return blocks[0]->getX();
}

int Snake::getY()
{
	return blocks[0]->getY();
}

void Snake::setDirection(int dir)
{
	direction = dir;
}

int Snake::getDirection()
{
	return direction;
}

void Snake::draw(HDC hdc, int x, int y)
{
	for(int i=0; i<length; i++)
		Rectangle(hdc, x+blocks[i]->getX()*20, y+blocks[i]->getY()*20, x+blocks[i]->getX()*20+20, y+blocks[i]->getY()*20+20);
}
